package com.ruoyi.system.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.material.domain.ZnMaterialAttribute;
import com.ruoyi.material.service.IZnMaterialAttributeService;
import com.ruoyi.system.domain.ZnCompanyConfig;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IZnCompanyConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ZnTenantMapper;
import com.ruoyi.system.domain.ZnTenant;
import com.ruoyi.system.service.IZnTenantService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 租户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-29
 */
@Service
public class ZnTenantServiceImpl implements IZnTenantService 
{
    @Autowired
    private ZnTenantMapper znTenantMapper;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IZnMaterialAttributeService znMaterialAttributeService;
    @Autowired
    private IZnCompanyConfigService znCompanyConfigService;
    /**
     * 查询租户管理
     * 
     * @param id 租户管理主键
     * @return 租户管理
     */
    @Override
    public ZnTenant selectZnTenantById(Long id)
    {
        return znTenantMapper.selectZnTenantById(id);
    }

    /**
     * 查询租户管理列表
     * 
     * @param znTenant 租户管理
     * @return 租户管理
     */
    @Override
    public List<ZnTenant> selectZnTenantList(ZnTenant znTenant)
    {

        return znTenantMapper.selectZnTenantList(znTenant);
    }

    /**
     * 新增租户管理
     * 
     * @param znTenant 租户管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertZnTenant(ZnTenant znTenant)
    {
        SysUser user=new SysUser();
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setUserName(znTenant.getLoginName());
        user.setNickName(znTenant.getLoginName());
        user.setStatus("0");

        Long[] roleIds=new Long[]{2l};
        user.setRoleIds(roleIds);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        user.setUserType("01");
        userService.insertUser(user);
        user.setTenantId(user.getUserId());
        /**
         * @Author chenmingming
         * @Description //TODO 更新租户ID
         * @Date 10:36 2021/12/31
         * @Param [znTenant]
         * @return com.ruoyi.common.core.domain.AjaxResult
         **/

        znTenant.setEnabled(0);//默认启用
        znTenant.setTenantId(user.getTenantId());
        znTenant.setCreateTime(DateUtils.getNowDate());
        int i=znTenantMapper.insertZnTenant(znTenant);
        /**
         * 创建多属性
         */
        ZnMaterialAttribute manyColorAttribute=new ZnMaterialAttribute();
        manyColorAttribute.setDeleteFlag("0");
        manyColorAttribute.setTenantId(user.getUserId());
        manyColorAttribute.setAttributeField("manyColor");
        manyColorAttribute.setAttributeName("多颜色");
        manyColorAttribute.setAttributeValue("红色|橙色|黄色|绿色|蓝色|紫色");
        znMaterialAttributeService.insertZnMaterialAttribute(manyColorAttribute);
        ZnMaterialAttribute manySizeAttribute=new ZnMaterialAttribute();
        manySizeAttribute.setDeleteFlag("0");
        manySizeAttribute.setTenantId(user.getUserId());
        manySizeAttribute.setAttributeField("manySize");
        manySizeAttribute.setAttributeName("多尺寸1");
        manySizeAttribute.setAttributeValue("S|M|L|XL|XXL|XXXL");
        znMaterialAttributeService.insertZnMaterialAttribute(manySizeAttribute);
        ZnMaterialAttribute   other1Attribute=new ZnMaterialAttribute();
        other1Attribute.setDeleteFlag("0");
        other1Attribute.setTenantId(user.getUserId());
        other1Attribute.setAttributeField("other1");
        other1Attribute.setAttributeName("自定义1");
        other1Attribute.setAttributeValue("小米|华为");
        znMaterialAttributeService.insertZnMaterialAttribute(other1Attribute);
        ZnMaterialAttribute  other2Attribute=new ZnMaterialAttribute();
        other2Attribute.setDeleteFlag("0");
        other2Attribute.setTenantId(user.getUserId());
        other2Attribute.setAttributeField("other2");
        other2Attribute.setAttributeName("自定义2");
        other2Attribute.setAttributeValue("");
        znMaterialAttributeService.insertZnMaterialAttribute(other2Attribute);
        ZnMaterialAttribute other3Attribute=new ZnMaterialAttribute();
        other3Attribute.setDeleteFlag("0");
        other3Attribute.setTenantId(user.getUserId());
        other3Attribute.setAttributeField("other3");
        other3Attribute.setAttributeName("自定义3");
        other3Attribute.setAttributeValue("");
        znMaterialAttributeService.insertZnMaterialAttribute(other3Attribute);
        /*List<ZnMaterialAttribute> list = znMaterialAttributeService.selectZnMaterialAttributeList(znMaterialAttribute);
        */
        /**
         * 创建公司配置信息
         */
        ZnCompanyConfig znCompanyConfig=new ZnCompanyConfig();
        String companyName =  znTenant.getCompanyName().trim();
        if(StringUtils.isNotBlank(companyName)){
            znCompanyConfig.setCompanyName(companyName);
        }else{
            companyName = "总部";
        }
        znCompanyConfig.setCompanyName(companyName);
      /*  znCompanyConfig.setCompanyName("公司");*/
        znCompanyConfig.setCustomerFlag("0");
        znCompanyConfig.setCompanyFax("0");
        znCompanyConfig.setDeleteFlag("0");
        znCompanyConfig.setDepotFlag("0");
        znCompanyConfig.setTenantId(user.getTenantId());
        znCompanyConfigService.insertZnCompanyConfig(znCompanyConfig);
        /**
         * 创建个 默认顶级部门
         */
        SysDept sysDept=new SysDept();
        sysDept.setParentId(0L);
        sysDept.setAncestors("0");
        sysDept.setDelFlag("0");
        sysDept.setStatus("0");
        sysDept.setDeptName(companyName);
        sysDept.setOrderNum("0");
        sysDept.setCreateBy(user.getUserName());
        sysDept.setTenantId(user.getTenantId());
        sysDept.setCreateTime(new Date());
        deptMapper.insertDept(sysDept);
        /**
         * 更新user信息
         */
        user.setDeptId(sysDept.getDeptId());
        userService.updateUserProfile(user);

        if(i>0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 修改租户管理
     * 
     * @param znTenant 租户管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateZnTenant(ZnTenant znTenant)
    {
        if(znTenant.getEnabled() ==2){//
            userService.updateUserStatusByTenantId(0,znTenant.getTenantId());//帐号状态（0正常 1停用）
            znTenant.setEnabled(0);
        }
        return znTenantMapper.updateZnTenant(znTenant);
    }

    /**
     * 批量删除租户管理
     * 
     * @param ids 需要删除的租户管理主键
     * @return 结果
     */
    @Override
    public int deleteZnTenantByIds(Long[] ids)
    {
        return znTenantMapper.deleteZnTenantByIds(ids);
    }

    /**
     * 删除租户管理信息
     * 
     * @param id 租户管理主键
     * @return 结果
     */
    @Override
    public int deleteZnTenantById(Long id)
    {
        return znTenantMapper.deleteZnTenantById(id);
    }

    @Override
    @Transactional
    public int enableTenant(Long[] ids, Integer enable) {
        Map map=new HashMap<>();
        map.put("id",ids);
        map.put("enable",enable);
        Map map2=new HashMap<>();
        for(Long id:ids){
          ZnTenant znTenant=znTenantMapper.selectZnTenantById(id);
          if(znTenant!=null){
//              SysUser sysUser=new SysUser();
//              /*map2.put("enable",enable);
//              map2.put("id",ids);*/
//
//              sysUser.setStatus(enable+"");
//              sysUser.setUserId(znTenant.getTenantId());
//              userService.updateUserProfile(sysUser);
              userService.updateUserStatusByTenantId(enable,znTenant.getTenantId());//帐号状态（0正常 1停用）
          }
        }

        return znTenantMapper.enableTenant(map);
    }
    /**
     * 租户到期禁用账号定时器
     * 1、查询当前启用的到期租户列表；
     * 2、将到期租户状态转为到期 2 ，租户下的账号全部转为禁用。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disabled() {
        ZnTenant znTenant = new ZnTenant();
//        znTenant.setEnabled(0);
        znTenant.getParams().put("isTimeOut",true);
        List<ZnTenant> list = znTenantMapper.selectZnTenantList(znTenant);
        for (ZnTenant temp:list) {
            temp.setEnabled(2);
            znTenantMapper.updateZnTenant(temp);
            userService.updateUserStatusByTenantId(2,temp.getTenantId());//帐号状态（0正常 1停用）
        }
    }
}
